package org.common.convert.tohtml;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.common.convert.util.FileHelper;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 将xls转换为html
 */
public class XlsToHtml {
    /**
     * 将xls转换为html
     * @param inputFilePath 源xls路径
     * @param outputFilePath 生成html路径
     * @throws Exception
     */
    public static void xlsToHtml(String inputFilePath, String outputFilePath) throws Exception
    {
        System.out.println("outputFilePath:"+outputFilePath);
        String inputFileName =inputFilePath;
        InputStream input=new FileInputStream(inputFileName);
        HSSFWorkbook excelBook=new HSSFWorkbook(input);
        ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
        excelToHtmlConverter.processWorkbook(excelBook);
        // 处理图片

        String path = FileHelper.getPath(inputFileName);
        Document htmlDocument =excelToHtmlConverter.getDocument();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource (htmlDocument);
        StreamResult streamResult = new StreamResult (outStream);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty (OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty (OutputKeys.INDENT, "yes");
        serializer.setOutputProperty (OutputKeys.METHOD, "html");
        serializer.transform (domSource, streamResult);
        outStream.close();

        String content = new String (outStream.toByteArray(),"UTF-8" );
        File outFile =  new File(outputFilePath);
        FileUtils.writeStringToFile(outFile, content, "utf-8");

    }
}
